package cn.boy.gui;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.boy.domain.Adminstrator;
import cn.boy.domain.Student;
import cn.boy.gui.adminstrator.AdminstratorMainActivity;
import cn.boy.gui.student.StudentMainAcitivity;
import cn.boy.home.HomeApplication;
import cn.boy.home.R;
import cn.boy.service.HomeService;

public class LoginActivity extends Activity implements View.OnClickListener{
	
	protected static final String TAG = "LoginActivity";
	EditText txtName;
	EditText txtpassword;
	CheckBox remember;
	Spinner spinner;
	Button registerButton;
	Button loginButton;
	
	HomeApplication application;
	ProgressDialog pd;
	
	public static final int LOGIN_NET_ERROR = 0;
	public static final int LOGIN_SUCCESS = 1;
	public static final int LOGIN_FAIL = 2;
	
	String retValue;
	
	String[] roles = {"选择角色","学生","管理员"}; 
	String role ;
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		application = (HomeApplication)getApplicationContext();
		
		findViews();
		
		initSpinner();
		
		getLoginParams();
		
		checkNet();
		
		loginButton.setOnClickListener(this);
		
		registerButton.setOnClickListener(this);
	}



	/**
	 * chect the state of internet
	 */
	private void checkNet() {

		ConnectivityManager conMan = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		if (mobile.equals(State.CONNECTED)) {
			Log.i(TAG,"---mobile connected---");
		} else if (wifi.equals(State.CONNECTED)) {
			Log.i(TAG,"---wifi connected---");
		} else {
			Log.i(TAG,"---no net connected---");
			Toast.makeText(this, R.string.no_net, 1).show();
		}
		
	}
	
	private void initSpinner() {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, roles);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				parent.setVisibility(View.VISIBLE);
				TextView v = (TextView) view;
				if (v != null) {
					role = v.getText().toString();
				}
				Log.i(TAG, role);
				
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}




	private void findViews() {
		txtName = (EditText)findViewById(R.id.et_name);
		txtpassword = (EditText)findViewById(R.id.et_password);
		remember = (CheckBox)findViewById(R.id.cb_remember);
		spinner = (Spinner)findViewById(R.id.spinner_role);
		registerButton = (Button)findViewById(R.id.btn_register);
		loginButton = (Button)findViewById(R.id.btn_login);
	}



	public void onClick(View v) {

		switch(v.getId()){
		case R.id.btn_login:
			if(!role.equals("选择角色")){
				String name = txtName.getText().toString().trim();
				String password = txtpassword.getText().toString().trim();
				login(name, password);
			}else{
				Toast.makeText(this, R.string.select_role, 1).show();
			}
			break;
		case R.id.btn_register:
			Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
			startActivity(intent);
			break;
			
		}
		
	}
	
	public void login(final String name,final String password){
		if(!TextUtils.isEmpty(name)&& !TextUtils.isEmpty(password)){
			
			showDialog();
			
			new Thread(new Runnable() {
				public void run() {
					try {
						retValue = HomeService.login(name, password,role);
						if(!retValue.equals("")){
							sendHandlerMessage(LOGIN_SUCCESS);
						}else{
							sendHandlerMessage(LOGIN_FAIL);
						}
					} catch (Exception e) {
						Log.e(TAG, e.toString());
						sendHandlerMessage(LOGIN_NET_ERROR);
					}
				}
			}).start(); // must start
		}else{
			Toast.makeText(this, R.string.empty, 1).show();
		}
	}
	
	private void sendHandlerMessage(int what) {
		Message msg = handler.obtainMessage(what);
		handler.sendMessage(msg);
		
	}

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(pd!=null){
				pd.dismiss();
			}
			switch(msg.what){
			case 0:
				Toast.makeText(LoginActivity.this, R.string.net_unreacgabke, 1).show();
				break;
			case 1:
				Toast.makeText(LoginActivity.this, R.string.success, 1).show();
				saveLoginParams();
				JSONObject json = null;
				try {
					json = new JSONObject(retValue);
				} catch (JSONException e) {
					Log.e(TAG, e.toString());
				}
				Log.i(TAG, "role information --->>" + json);
				mappingEntity(json);
				launchActivity();
				break;
			case 2:
				Toast.makeText(LoginActivity.this, R.string.fail, 1).show();
				break;
			}
		};
	};
	
	private void launchActivity() {
		Intent intent ;
		if(role.equals("学生")){// dump to student main Activity
			intent = new Intent(this, StudentMainAcitivity.class);
		}else{// dump to adminstrator main Activity
			intent = new Intent(this, AdminstratorMainActivity.class);
		}
		startActivity(intent);
		finish();
	}


	private void showDialog() {
		pd = new ProgressDialog(LoginActivity.this); 
		pd.setMessage(getResources().getString(R.string.login_prompt));
		pd.show();
	}

	private void mappingEntity(JSONObject json) {
		if(role.equals("学生")){
			try {
				String no = json.getString("no");
				String name = json.getString("name");
				String sex = json.getString("sex");
				String age = json.getString("age");
				String dormitoryNO = json.getString("dormitoryNO");
				String classInfo = json.getString("classInfo");
				Student student = new Student(no, name, "", sex, age, dormitoryNO, classInfo);
				application.setStudent(student);
			} catch (JSONException e) {
				Log.e(TAG, e.toString());
			}
		}else{// Adminstrator
			try {
				String no = json.getString("no");
				String name = json.getString("name");
				String sex = json.getString("sex");
				String age = json.getString("age");
				String department = json.getString("department");
				Adminstrator admin = new Adminstrator(no, name, "", sex, age, department);
				application.setAdmin(admin);
			} catch (JSONException e) {
				Log.e(TAG, e.toString());
			}
		
		}
	}
	
	// 获取登陆数据
	private void getLoginParams() {
		SharedPreferences sp = getSharedPreferences("loginparam",
				Activity.MODE_PRIVATE);
		boolean isChecked = sp.getBoolean("isChecked", false);
		if (isChecked) {
			txtName.setText(sp.getString("userName", ""));
			txtpassword.setText(sp.getString("userPassword", ""));
			spinner.setSelection(sp.getInt("position", 0));
			remember.setChecked(true);
			role = sp.getString("role", "");
		}
	}

	// 保存登陆数据
	private void saveLoginParams() {
		SharedPreferences sp = getSharedPreferences("loginparam",
				Activity.MODE_PRIVATE);
		boolean isChecked = remember.isChecked();
		if (isChecked) {
			sp.edit()
					.putString("userName",
							txtName.getText().toString().trim())
					.putString("userPassword",
							txtpassword.getText().toString().trim())
					.putString("role", role)
					.putInt("position", spinner.getSelectedItemPosition())
					.putBoolean("isChecked", true).commit();
		} else {
			sp.edit().putString("userName", "").putString("userPassword", "")
					.putInt("position", 0).putBoolean("isChecked", false)
					.commit();
		}
	}
	
	
/*	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			android.os.Process.killProcess(android.os.Process.myPid());
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}*/
	
}
